/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package th.stripes.services;

import com.google.inject.Inject;
import com.oas.thit._this.balenq.xsd.BalanceEnquiryRequestBody;
import com.oas.thit._this.balenq.xsd.BalanceEnquiryResponseBody;
import com.oas.thit._this.profile.depositor.update.xsd.DepositorProfileUpdateRequestBody;
import com.oas.thit._this.profile.depositor.xsd.DepositorProfileResponseBody;
import com.oas.thit._this.stmt.xsd.StatementRequestBody;
import com.oas.thit._this.stmt.xsd.StatementResponseBody;
import com.oas.thit._this.stmt.xsd.StatementResponseLineItem;
import com.oas.thit._this.xsd.THISBaseDataElementBody;
import com.oas.thit.xmlmessage.xsd.Header;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import javax.servlet.http.HttpSession;
import javax.xml.bind.JAXBElement;
import th.dao.KodJantinaDAO;
import th.dao.KodKahwinDAO;
import th.dao.KodNegeriDAO;
import th.dao.KodPekerjaanDAO;
import th.dao.KodSektorPekerjaanDAO;
import th.dao.KodStatusDAO;
import th.dao.KodUrusanDAO;
import th.dao.KodWarganegaraDAO;
import th.dao.PoskodDAO;
import th.manager.AkaunManager;
import th.manager.SMSgatewayManager;
import th.manager.SejarahTransaksiManager;
import th.model.Deposit;
import th.model.InfoAudit;
import th.model.KodKebenaranTransaksi;
import th.model.Pengguna;
import th.model.PenyataAkaun;
import th.model.Poskod;
import th.model.SejarahTransaksi;
import th.stripes.webservice.WebServiceUtil;

/**
 *
 * @author fikri
 */
public class DepositService {

    private static final String SUCCESSFUL = "0000";
    private static final String SYSTEM_ERROR = "9999";   
    private static final String INVALID_ACC_IC = "9000";  
    private static final String BAL_ENQ_MSG_ID = "TPBALENQWD01";
    private static final String STAT_ENQ_MSG_ID = "TPTHSTMTWD01";
    private static final String PROFILE_ENQ_MSG_ID = "TPDPPROFWD01";
    private static final String UPD_PROFILE_MSG_ID = "TPDPPROFWD02";
    private static final String ADD_ACC_MSG_ID = "TPUSRMGTWD02";
    private static final String HEADER_ID_BALANCE_ENQUIRY = "THSBENQ";
    private static final String HEADER_ID_STATEMENT_ENQUIRY = "THSSTMT";
    private static final String HEADER_ID_PROFILE_ENQUIRY = "THSDPQR";
    private static final String HEADER_ID_UPD_PROFILE = "THSDPUP";
    private static final String HEADER_ID_ADD_ACCOUNT = "THSCUVL";
    private static final String VAL_ACC_MSG_ID = "TPUSRMGTWD03";
    private static final String HEADER_ID_VAL_ACCOUNT = "THSACVL";
    //private static String STAT_CARD_ENQ_MSG_ID = "TPCTMTMWD01"; //-20/6/2014
    private static final String STAT_CARD_ENQ_MSG_ID = "TPTHCTMTWD01"; //-02/7/2014
    private static final String HEADER_ID_CARD_STATEMENT_ENQUIRY = "THSCTMT";//-26/6/2014

    private static final String IPDKWSP_ACCOUNT = "11";
    private static final String CUSTODIAN_ACCOUNT = "02";

    private static final String HEADER_ID_VAL_FAV_ACCOUNT = "THSACVL";
    private static final String VAL_FAV_ACC_MSG_ID = "TPUSRMGTWD04"; //add 25/10/2014
    private static final String ACC_STS_EPF = "9206";
    private static final String ADD_FAV_ACC = "ADDFAV"; // ADD 18/09/2014
    private static final String HEADER_ID_ADD_FAV_ACC = "THFAVADD"; // ADD 18/09/2014
    private static final String HEADER_ID_EDIT_FAV_ACC = "THFAVEDIT"; // ADD 26/09/2014
    private static final String EDIT_FAV_ACC = "EDITFAV"; // ADD 18/09/2014
    
    private com.oas.thit._this.services.THISServices service = new com.oas.thit._this.services.THISServices();
    private com.oas.thit._this.services.THISServicesPortType port = service.getTHISServicesHttpSoap11Endpoint();
    
    @Inject
    private WebServiceUtil webUtil;    
    
    @Inject
    SMSgatewayManager sMSgatewayManager;
    
    @Inject
    private SejarahTransaksiManager sejarahTransaksiManager;
    
    @Inject 
    private KodNegeriDAO kodNegeriDAO;
    
    @Inject
    private KodJantinaDAO kodJantinaDAO;
    
    @Inject
    private KodKahwinDAO kodKahwinDAO;
    
    @Inject
    private PoskodDAO poskodDAO;
    
    @Inject
    private KodPekerjaanDAO kodPekerjaanDAO;
    
    @Inject
    private KodSektorPekerjaanDAO kodSektorPekerjaanDAO;
    
    @Inject
    private KodWarganegaraDAO kodWarganegaraDAO;
    
    @Inject
    private KodUrusanDAO kodUrusanDAO ;
    
    @Inject
    private KodStatusDAO kodStatusDAO;
    
    @Inject 
    private AkaunManager akaunManager;
    

    public String inquiryBalance(Deposit deposit, 
            Pengguna pengguna, String responseCode, String idSessi) {
        
        SejarahTransaksi sejarahTransaksi = new SejarahTransaksi(); 

        com.oas.thit._this.services.THISServices service = new com.oas.thit._this.services.THISServices();
        com.oas.thit._this.services.THISServicesPortType port = service.getTHISServicesHttpSoap11Endpoint();
        // TODO initialize WS operation arguments here
        com.oas.thit._this.balenq.xsd.BalanceEnquiryRequest req = new com.oas.thit._this.balenq.xsd.BalanceEnquiryRequest();
        com.oas.thit._this.balenq.xsd.ObjectFactory objFactory = new com.oas.thit._this.balenq.xsd.ObjectFactory();
        com.oas.thit._this.xsd.ObjectFactory _objFactory = new com.oas.thit._this.xsd.ObjectFactory();

        req.setHeader(webUtil.createHeader(BAL_ENQ_MSG_ID, HEADER_ID_BALANCE_ENQUIRY));
        BalanceEnquiryRequestBody reqBody = objFactory.createBalanceEnquiryRequestBody();

        if (deposit.getNoKp().equals(deposit.getNoKpDari())) {

            reqBody.setTHAcct(_objFactory.createTHISBaseDataElementBodyTHAcct(deposit.getNoAkaunDari()));
            reqBody.setTHICNo(_objFactory.createTHISBaseDataElementBodyTHICNo(deposit.getNoKpDari()));

        } else {

            reqBody.setParentAcct(objFactory.createBalanceEnquiryRequestBodyParentAcct(deposit.getNoAkaun()));
            reqBody.setParentICNo(objFactory.createBalanceEnquiryRequestBodyParentICNo(deposit.getNoKp()));
            reqBody.setTHAcct(_objFactory.createTHISBaseDataElementBodyTHAcct(deposit.getNoAkaunDari()));
            reqBody.setTHICNo(_objFactory.createTHISBaseDataElementBodyTHICNo(deposit.getNoKpDari()));
        }

        JAXBElement<BalanceEnquiryRequestBody> jReqBody = objFactory.createBalanceEnquiryRequestBody(reqBody);
        req.setBody(jReqBody);

        com.oas.thit._this.balenq.xsd.BalanceEnquiryResponse result = port.balanceEnquiry(req);
        Header header = result.getHeader().getValue();
        responseCode = header.getResponseCode().getValue();

        sejarahTransaksi.setPengguna(pengguna);
        sejarahTransaksi.setTrhMasuk(new Date());
        sejarahTransaksi.setUrusan(kodUrusanDAO.findById(BAL_ENQ_MSG_ID));
        sejarahTransaksi.setIdSessi(idSessi);
        sejarahTransaksi.setStatus(kodStatusDAO.findById(responseCode));
        sejarahTransaksi.setNilaiDalaman1(header.getTxid().getValue().trim());
        
        if (responseCode.equals(SUCCESSFUL)) {
            BalanceEnquiryResponseBody resp = result.getBody().getValue();
            BigDecimal amaun = new BigDecimal(resp.getTHAmount().getValue()).multiply(new BigDecimal("0.01"));
            deposit.setBaki(new BigDecimal(amaun.toString()));
            deposit.setNoAkaun(resp.getTHAcct().getValue());
            deposit.setNama(resp.getTHName().getValue());
            sejarahTransaksi.setAmaun(deposit.getBaki());
        }
        
        sejarahTransaksiManager.saveSejarahTransaksi(sejarahTransaksi);

        return responseCode;
    }
    
    public String depositorProfile(Deposit deposit, 
            Pengguna pengguna, String responseCode, String idSessi) throws ParseException{
    
        
        responseCode="";
    DateFormat format = new SimpleDateFormat("yyyyMMdd");        
         // Call Web Service Operation
            com.oas.thit._this.services.THISServices service = new com.oas.thit._this.services.THISServices();
            com.oas.thit._this.services.THISServicesPortType port = service.getTHISServicesHttpSoap11Endpoint();
            // TODO initialize WS operation arguments here
            com.oas.thit._this.xsd.THISRequest req = new com.oas.thit._this.xsd.THISRequest();
            com.oas.thit._this.xsd.ObjectFactory objFactory = new com.oas.thit._this.xsd.ObjectFactory();
            
            req.setHeader( webUtil.createHeader(PROFILE_ENQ_MSG_ID, HEADER_ID_PROFILE_ENQUIRY) );
            
            THISBaseDataElementBody reqBody = objFactory.createTHISBaseDataElementBody();
            reqBody.setTHAcct(objFactory.createTHISBaseDataElementBodyTHAcct(deposit.getNoAkaun()));
            reqBody.setTHICNo(objFactory.createTHISBaseDataElementBodyTHICNo(deposit.getNoKp()));
            
            JAXBElement<THISBaseDataElementBody> jReqBody =  objFactory.createTHISRequestBody(reqBody);
            req.setBody(jReqBody);
            
            // TODO process result here
            com.oas.thit._this.profile.depositor.xsd.DepositorProfileResponse result = port.depositorProfileQuery(req);
            Header header = result.getHeader().getValue();
            responseCode = header.getResponseCode().getValue();
            if (responseCode.equals(SUCCESSFUL)) {
                DepositorProfileResponseBody resp = result.getBody().getValue();
                if ( resp != null ) {
                    deposit.setNoAkaun( resp.getTHAcct().getValue().trim() );
                    deposit.setNoKp( resp.getTHICNo().getValue().trim() );
                    deposit.setNama( resp.getTHName().getValue().trim() );
                    deposit.setJantina( kodJantinaDAO.findById( resp.getTHGender().getValue().trim()));
                    if(resp.getTHDOB().getValue().trim().equals("00010101"))
                        deposit.setTarikhLahir(null);
                    else 
                    deposit.setTarikhLahir( format.parse(resp.getTHDOB().getValue()));
                    deposit.setKahwin( kodKahwinDAO.findById(resp.getTHMarital().getValue().trim()));
                    deposit.setAlamat1( resp.getTHAddress1().getValue().trim());
                    deposit.setAlamat2( resp.getTHAddress2().getValue().trim() );
                    deposit.setAlamat3( resp.getTHAddress3().getValue().trim() );
                    if(resp.getTHPoskod().getValue()!=null){
                        Poskod poskod = poskodDAO.findById(resp.getTHPoskod().getValue().trim());
                        deposit.setPoskod( poskod.getPoskod());
                        deposit.setAlamat4(poskod.getNama());//deskripsi poskod
                    }
                    deposit.setNegeri(kodNegeriDAO.findById(resp.getTHState().getValue().trim()));
                    deposit.setNoTel1( resp.getTHPhoneHome().getValue().trim() );
                    deposit.setNoTel2( resp.getTHPhoneOffice().getValue().trim() );
                    deposit.setNoTel3( resp.getTHPhoneMobile().getValue().trim() );
                    deposit.setEmail(resp.getTHemail().getValue().trim()); 
                    
                    deposit.setNamaDatuk( resp.getTHMother().getValue().trim() );
                    if(resp.getTHEthnic().getValue()!=null)
                        deposit.setBangsa(resp.getTHEthnic().getValue().trim());                    
                    deposit.setWarganegara(kodWarganegaraDAO.findById(resp.getTHNationality().getValue().trim()));
                    deposit.setSektorPekerjaan(kodSektorPekerjaanDAO.findById(resp.getTHEmploy().getValue().trim()));
                
                
            } 
            
            }
    
     return responseCode;
    }
    
    public String saveDepositorProfile(Deposit deposit, 
            Pengguna pengguna, String responseCode, String idSessi){
    
        boolean proceed=true; //temp
        InfoAudit ia = new InfoAudit();
        ia.setDimasukOleh(pengguna);
        ia.setTarikhMasuk(new Date());
        responseCode = "";
        SejarahTransaksi sejarahTransaksi = new SejarahTransaksi(); 
        //HttpSession ses = context.getRequest().getSession();
        KodKebenaranTransaksi kodKebenaranTransaksi = sMSgatewayManager.findKodKebenaranTransaksiBySessionId(idSessi, HEADER_ID_UPD_PROFILE, "Y");
        if(kodKebenaranTransaksi != null){            
            if(kodKebenaranTransaksi.getSah().equals("Y") && kodKebenaranTransaksi.getKodKebenaranTransaksi().equals(deposit.getTacNumber())){
                kodKebenaranTransaksi.setInfoAudit(ia);
                kodKebenaranTransaksi.setSah("N");  
//          if(proceed){
//              if(proceed){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                try { 
                    // Call Web Service Operation                    
                    com.oas.thit._this.services.THISServices service = new com.oas.thit._this.services.THISServices();
                    com.oas.thit._this.services.THISServicesPortType port = service.getTHISServicesHttpSoap11Endpoint();
                    // TODO initialize WS operation arguments here
                    com.oas.thit._this.profile.depositor.update.xsd.DepositorProfileUpdateRequest req 
                            = new com.oas.thit._this.profile.depositor.update.xsd.DepositorProfileUpdateRequest();

                    req.setHeader( webUtil.createHeader(UPD_PROFILE_MSG_ID, HEADER_ID_UPD_PROFILE ) );
                    com.oas.thit._this.profile.depositor.update.xsd.ObjectFactory objFactory = new com.oas.thit._this.profile.depositor.update.xsd.ObjectFactory();  
                    com.oas.thit._this.xsd.ObjectFactory _objFactory = new com.oas.thit._this.xsd.ObjectFactory(); 
                    DepositorProfileUpdateRequestBody reqBody = objFactory.createDepositorProfileUpdateRequestBody();
                    reqBody.setTHAcct( _objFactory.createTHISBaseDataElementBodyTHAcct(deposit.getNoAkaun()) );
                    reqBody.setTHICNo( _objFactory.createTHISBaseDataElementBodyTHICNo( deposit.getNoKp()) );
                    reqBody.setTHName( _objFactory.createTHISResponseBodyTHName( deposit.getNama() ));
                    if(deposit.getJantina()!=null)
                       reqBody.setTHGender( objFactory.createDepositorProfileUpdateRequestBodyTHGender( deposit.getJantina().getKod() ));
                    else
                        reqBody.setTHGender( objFactory.createDepositorProfileUpdateRequestBodyTHGender(""));
                    if(deposit.getTarikhLahir()!=null)
                        reqBody.setTHDOB( objFactory.createDepositorProfileUpdateRequestBodyTHDOB( sdf.format(deposit.getTarikhLahir())) );
                    if(deposit.getKahwin()!=null)
                        reqBody.setTHMarital( objFactory.createDepositorProfileUpdateRequestBodyTHMarital( deposit.getKahwin().getKod()));
                    else
                        reqBody.setTHMarital( objFactory.createDepositorProfileUpdateRequestBodyTHMarital(""));
                    reqBody.setTHAddress1( _objFactory.createTHProfileRequestBodyTHAddress1( deposit.getAlamat1()) );
                    reqBody.setTHAddress2( _objFactory.createTHProfileRequestBodyTHAddress2( deposit.getAlamat2()) );
                    reqBody.setTHAddress3( _objFactory.createTHProfileRequestBodyTHAddress3( deposit.getAlamat3()) );
                    reqBody.setTHPoskod( _objFactory.createTHProfileRequestBodyTHPoskod( deposit.getPoskod()) );
                    if(deposit.getNegeri()!=null)
                        reqBody.setTHState( _objFactory.createTHProfileRequestBodyTHState( deposit.getNegeri().getCode()) );
                    else
                        reqBody.setTHState( _objFactory.createTHProfileRequestBodyTHState(""));
                    reqBody.setTHPhoneHome( objFactory.createDepositorProfileUpdateRequestBodyTHPhoneHome( deposit.getNoTel1()) );
                    reqBody.setTHPhoneOffice( objFactory.createDepositorProfileUpdateRequestBodyTHPhoneOffice( deposit.getNoTel2()) );
                    reqBody.setTHPhoneMobile( objFactory.createDepositorProfileUpdateRequestBodyTHPhoneMobile( deposit.getNoTel3()) );
                    reqBody.setTHemail( objFactory.createDepositorProfileUpdateRequestBodyTHemail( deposit.getEmail() ));
                    reqBody.setTHMother( objFactory.createDepositorProfileUpdateRequestBodyTHMother( deposit.getNamaDatuk()) );                    
                    if(deposit.getSektorPekerjaan()!=null)
                        reqBody.setTHEmploy( objFactory.createDepositorProfileUpdateRequestBodyTHEmploy( deposit.getSektorPekerjaan().getKod()) );
                    else
                        reqBody.setTHEmploy( objFactory.createDepositorProfileUpdateRequestBodyTHEmploy(""));                    
                    if(deposit.getWarganegara()!=null)
                        reqBody.setTHNationality(objFactory.createDepositorProfileUpdateRequestBodyTHNationality(deposit.getWarganegara().getKod()));
                    else
                        reqBody.setTHNationality(objFactory.createDepositorProfileUpdateRequestBodyTHNationality(""));
                    reqBody.setTHEthnic(objFactory.createDepositorProfileUpdateRequestBodyTHEthnic((deposit.getBangsa())));
                    JAXBElement<DepositorProfileUpdateRequestBody> jReqBody = objFactory.createDepositorProfileUpdateRequestBody(reqBody);
                    req.setBody( jReqBody );
                    // TODO process result here
                    com.oas.thit._this.profile.depositor.xsd.DepositorProfileResponse result = port.depositorProfileUpdate(req);
                    Header header = result.getHeader().getValue();
                    responseCode = header.getResponseCode().getValue();
                    sejarahTransaksi.setPengguna(pengguna);
                    sejarahTransaksi.setTrhMasuk(new Date());
                    sejarahTransaksi.setUrusan(kodUrusanDAO.findById(UPD_PROFILE_MSG_ID));
                    sejarahTransaksi.setIdSessi(idSessi);//(getContext().getRequest().getSession().getId());
                    sejarahTransaksi.setStatus(kodStatusDAO.findById(responseCode));
                    sejarahTransaksi.setNilaiDalaman1(header.getTxid().getValue().trim());
                                           
                } catch (Exception ex) {        
                   // LOG.error("error {}", ex);
                    responseCode = SYSTEM_ERROR; 
                    //addSimpleError("" + responseManager.getResponseMessage(responseCode, UPD_PROFILE_MSG_ID));
                }
                sejarahTransaksiManager.saveSejarahTransaksi(sejarahTransaksi); 
              
            
        
            }else{ 
         //       addSimpleError("KOD PENGESAHAN TRANSAKSI(TAC) TIDAK SAH");
          //      return new JSP("deposit/view_updated_profile_TACrequest.jsp");
            }
        }else{
        //    addSimpleError("KOD PENGESAHAN TRANSAKSI(TAC) TIDAK SAH");
         //   return new JSP("deposit/view_updated_profile_TACrequest.jsp");
        }
        //sMSgatewayManager.saveTAC(kodKebenaranTransaksi);
     System.out.println("Status :"+responseCode);  
     return responseCode;
    }
                    
                   
    public String accountStatement(Deposit deposit, 
            Pengguna pengguna, String responseCode, String idSessi){
         
        
        String noAkaunPenjaga = "";
        String noKpPenjaga = "";
        

        //deposit.setNoKpDari(deposit.getNoKp());
        //deposit.setNoAkaunDari(deposit.getNoAkaun());
        //pengguna.getNoKp();
        
        if ((pengguna.getNoKp()).equals(deposit.getNoKpDari())) {
             deposit.setNoKpDari(deposit.getNoKp());
             deposit.setNoAkaunDari(deposit.getNoAkaun());
        } else {
            noAkaunPenjaga = akaunManager.getNoAkaun(pengguna.getNoKp(), "Y");
            noKpPenjaga = pengguna.getNoKp();
            
            deposit.setNoKpPenjaga(noKpPenjaga);
            deposit.setNoAkaunPenjaga(noAkaunPenjaga);
            deposit.setNoKpDari(deposit.getNoKp());
            deposit.setNoAkaunDari(deposit.getNoAkaun());
        }
         
        //add in 25092014
        deposit.setBulanPilihan(deposit.getBulanPilihan());
        
        
        
        // check status akaun
//        String getJnsAkaun = getJenisAkaun(deposit.getNoAkaunDari(), deposit.getNoKpDari());
//        if (getJnsAkaun!= null) {
//            if (getJnsAkaun.equals(CUSTODIAN_ACCOUNT)) {
//                 noAkaunPenjaga = akaunManager.getNoAkaun(pengguna.getNoKp(), "Y");
//                 noKpPenjaga = pengguna.getNoKp();
//            }
//        }
        
       
        
        DecimalFormat formatter = new DecimalFormat("#,###.##");
        SimpleDateFormat d = new SimpleDateFormat("dd/MM/yyyy");
        DateFormat dateformat = new SimpleDateFormat("yyyyMMdd");
        //DateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        
        SejarahTransaksi sejarahTransaksi = new SejarahTransaksi();
        
        //by selected month, get start and end date
        //selected month = 032014 MMyyyy
         String selectedMonth = deposit.getBulanPilihan();
         String month = selectedMonth.substring(0, 2);
         String year = selectedMonth.substring(5, 9);
         
         //get start date
         String firstDate = dateformat.format(getFirstDayOfMonth(month, year));
         String lastDate = dateformat.format(getLastDayOfMonth(month, year));
         
        try { 
            // Call Web Service Operation
            
            com.oas.thit._this.stmt.xsd.StatementRequest req = new com.oas.thit._this.stmt.xsd.StatementRequest();
            com.oas.thit._this.stmt.xsd.ObjectFactory objFactoryStmt = new com.oas.thit._this.stmt.xsd.ObjectFactory();
            com.oas.thit._this.xsd.ObjectFactory objFactory = new com.oas.thit._this.xsd.ObjectFactory();
            
            req.setHeader(webUtil.createHeader(STAT_ENQ_MSG_ID, HEADER_ID_STATEMENT_ENQUIRY));
            com.oas.thit._this.stmt.xsd.StatementRequestBody reqBody = new com.oas.thit._this.stmt.xsd.StatementRequestBody();
            
            reqBody.setTHAcct(objFactory.createTHISBaseDataElementBodyTHAcct(deposit.getNoAkaunDari()));
            reqBody.setTHICNo(objFactory.createTHISBaseDataElementBodyTHICNo(deposit.getNoKpDari()));
            reqBody.setTHStmtStartDate(objFactoryStmt.createStatementRequestBodyTHStmtStartDate(firstDate));
            reqBody.setTHStmtEndDate(objFactoryStmt.createStatementRequestBodyTHStmtEndDate(lastDate));
              
            JAXBElement<StatementRequestBody> jReqBody =  objFactoryStmt.createStatementRequestBody(reqBody);

            req.setBody(jReqBody);
            
            // TODO process result here
            com.oas.thit._this.stmt.xsd.StatementResponse result = port.statementRequest(req);
            Header header = result.getHeader().getValue();
            responseCode = header.getResponseCode().getValue();
            sejarahTransaksi.setPengguna(pengguna);
            sejarahTransaksi.setTrhMasuk(new Date());
            sejarahTransaksi.setUrusan(kodUrusanDAO.findById(STAT_ENQ_MSG_ID));
            sejarahTransaksi.setIdSessi(idSessi);
            sejarahTransaksi.setStatus(kodStatusDAO.findById(responseCode));
            sejarahTransaksi.setNilaiDalaman1(header.getTxid().getValue().trim());                    
            if (responseCode.equals(SUCCESSFUL)) {                
                StatementResponseBody resp = result.getBody().getValue();
                deposit.setNama(resp.getTHName().getValue());
                deposit.setAlamat1(resp.getTHAddress1().getValue());
                deposit.setAlamat2(resp.getTHAddress2().getValue());
                deposit.setAlamat3(resp.getTHAddress3().getValue());
                deposit.setPoskod(resp.getTHPoskod().getValue());
                //deposit.setTarikhTransaksi(dateformat.parse(resp.getTHStmtDate().getValue()));
                deposit.setNoAkaun( resp.getTHAcct().getValue() ); 
                deposit.setNoKp(resp.getTHICNo().getValue());
                deposit.setNegeriDesc(resp.getTHState().getValue().trim());
                List<StatementResponseLineItem> items  = resp.getLineItems();
                int itemsize = 0;
                if(items!=null && items.size()>0){
                    itemsize = items.size();
                    List<PenyataAkaun> senaraiAkaunDescending = new ArrayList<PenyataAkaun>(items.size());
                    List<PenyataAkaun> senaraiAkaunAscending = new ArrayList<PenyataAkaun>(items.size());
          
                    for ( StatementResponseLineItem item : items ) {
 
                        PenyataAkaun pa = new PenyataAkaun();
                        //Description
                        pa.setButiran(item.getTHTxDesription().getValue());
                        //Trxn Keluar
                        if(item.getTHTxKeluar().getValue()!=null && !item.getTHTxKeluar().getValue().trim().equals(""))
                            pa.setKeluar(new BigDecimal(item.getTHTxKeluar().getValue()).multiply(new BigDecimal("0.01")));
                        //Trxn Masuk
                        if(item.getTHTxMasuk().getValue()!=null && !item.getTHTxMasuk().getValue().trim().equals(""))
                            pa.setMasuk(new BigDecimal(item.getTHTxMasuk().getValue()).multiply(new BigDecimal("0.01")));
                        //balance
                        if(item.getTHBalance().getValue()!=null && !item.getTHBalance().getValue().trim().equals("")){
                            BigDecimal baki = new BigDecimal(item.getTHBalance().getValue()).multiply(new BigDecimal("0.01"));
                            pa.setBaki(baki);
                        }
//                        //trxn Keluar
//                        if(item.getTHTxKeluar().getValue()!=null && !item.getTHTxKeluar().getValue().trim().equals("")) {
//                            pa.setKeluar(item.getTHTxKeluar().getValue().trim());
//                        }
//                        //Trxn Masuk
//                        if(item.getTHTxMasuk().getValue()!=null && !item.getTHTxMasuk().getValue().trim().equals("")) {
//                            pa.setMasuk(item.getTHTxMasuk().getValue().trim());
//                        }
//                        //balance
//                        if(item.getTHBalance().getValue()!=null && !item.getTHBalance().getValue().trim().equals("")){
//                            pa.setBaki(item.getTHBalance().getValue().trim());
//                        }
                        //TrxnDate
                        pa.setTarikhTransaksi(dateformat.parse(item.getTHTxDate().getValue()));
                        //Seqnumber
                        Integer seqnum = Integer.parseInt(item.getTHSeq().getValue().trim());
                        senaraiAkaunAscending.add(seqnum.intValue()-1, pa); //set as ascending list
                    }

                    int m = 0;
                    for ( int i = itemsize; i>0; i--) {                    
                        PenyataAkaun pa = (PenyataAkaun)senaraiAkaunAscending.get(i-1);
                        senaraiAkaunDescending.add(m, pa);
                        m++;
                    }                
                    deposit.setSenaraiTransaksiAkaun(senaraiAkaunDescending); 
                }
                sejarahTransaksiManager.saveSejarahTransaksi(sejarahTransaksi);
//                getContext().getRequest().getSession().setAttribute("deposit", deposit);               
//                return new JSP("deposit/show_account_statement.jsp");
//                return new JSP("deposit/show_account_statement_main.jsp");
            }           
            
        } catch (Exception ex) {
        // TODO handle custom exceptions here
        //    LOG.error("error {}", ex);
            System.out.println("error = " +  ex);
            responseCode = SYSTEM_ERROR;
        }  
        sejarahTransaksiManager.saveSejarahTransaksi(sejarahTransaksi);
        //addSimpleError("" + responseManager.getResponseMessage(responseCode, STAT_ENQ_MSG_ID));
        //return new JSP("deposit/msg.jsp");
        
     return responseCode;
    }
    
      
    public Date getFirstDayOfMonth(String month, String year) {
    
        //Calendar cal = new GregorianCalendar(2013, 5, 0);
        int mth = Integer.parseInt(month);
        int yr = Integer.parseInt(year);
        Calendar cal = new GregorianCalendar(yr, mth-1, 1);
        Date date = cal.getTime();
        DateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        System.out.println("Date (First Day of Month): " + sdf.format(date));
        
        return date;
    }
    
    public Date getLastDayOfMonth(String month, String year) {
    
        //Calendar cal = new GregorianCalendar(2013, 5, 0);
        int mth = Integer.parseInt(month);
        int yr = Integer.parseInt(year);
        Calendar cal = new GregorianCalendar(yr, mth, 0);
        Date date = cal.getTime();
        DateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        System.out.println("Date (Last Day of Month): " + sdf.format(date));
        
        return date;
    }
}
